<template>
  <div id="signature-pad" class="signature-pad">
    <div class="description tc">签名区域</div>
    <div class="signature-pad--body">
      <canvas id="signature-canvas" width="800px" height="380px"></canvas>
    </div>
    <div class="signature-pad--footer">
      <button
        type="button"
        class="buttonclear clear"
        id="clear"
        data-action="clear"
      >
        重签
      </button>
      <button
        type="button"
        class="buttonclear clear"
        id="save"
        data-action="clear"
      >
        确定
      </button>
    </div>
  </div>
</template>

<script>
import SignaturePad from "signature_pad";
export default {
  mounted() {
    this.getSignaturePad();
  },
  methods: {
    getSignaturePad() {
      let canvas = document.getElementById("signature-canvas");
      let signaturePad = new SignaturePad(canvas, {
        backgroundColor: "#DEDEDE",
        penColor: "rgb(0, 0, 0)"
      });
      let saveButton = document.getElementById("save");
      let cancelButton = document.getElementById("clear");
      saveButton.addEventListener("click", function(event) {
        // 签名为空的判断
        if (signaturePad.isEmpty()) {
          alert("不能为空");
        }
        // signaturePad.jSignature('getData');
        let imgStr = signaturePad.toDataURL("image/png");
        console.log(imgStr, "imgStr");
        //获取到image的base64 可以把这个传到后台解析成图片
        //imgStr = ......
        //去掉data:image/png;base64,我们只要后面的部分iVBORw0KGgoAAAANSUhEUgAAAfgAAAL2CAYAAA......
        imgStr = imgStr.substring(22, imgStr.length);
      });
      cancelButton.addEventListener("click", function(event) {
        signaturePad.clear();
      });
      function resizeCanvas() {
        let ratio = Math.max(window.devicePixelRatio || 1, 1); // 清除画布
        canvas.width = canvas.offsetWidth * ratio;
        canvas.height = canvas.offsetHeight * ratio;
        canvas.getContext("2d").scale(ratio, ratio);
        signaturePad.clear();
      }
      resizeCanvas();
    }
  }
};
</script>

<style lang="less" scoped>
.signature-pad {
  width: 800px;
  height: 500px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}
.buttonclear {
  width: 50px;
  height: 30px;
  color: blue;
  background-color: rgb(197, 208, 233);
}
</style>
